package com.boarsoft.boar.office.group.biz;

import java.util.List;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.office.entity.OfficeGroupUser;
import com.boarsoft.boar.office.group.OfficeGroupUserBiz;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("workGroupUserBiz")
public class OfficeGroupUserBizImpl extends SimpleBizImpl implements OfficeGroupUserBiz {

	@Override
	@Transactional(readOnly = true)
	public PagedResult<OfficeGroupUser> list(String groupId, String key, String orderBy, int pageNo, int pageSize) {
		StringBuffer sb = new StringBuffer();
		sb.append(" from ").append(OfficeGroupUser.class.getName());
		sb.append(" o where o.groupId='").append(groupId).append("'");
		int total = dao.getTotal("select count(1)".concat(sb.toString()));
		List<OfficeGroupUser> lt = dao.list("select o".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<OfficeGroupUser>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void toggle(String groupId, String[] userIds, boolean isAdd) {
		StringBuilder sb = new StringBuilder();
		sb.append("from ").append(OfficeGroupUser.class.getName());
		sb.append(" where groupId=? and userId=?");
		Query<OfficeGroupUser> q = dao.createQuery(OfficeGroupUser.class, sb.toString());
		for (String uid : userIds) {
			q.setParameter(0, groupId);
			q.setParameter(1, uid);
			OfficeGroupUser o = q.uniqueResult();
			if (o == null) {
				if (isAdd) {
					o = new OfficeGroupUser();
					o.setUserId(uid);
					o.setGroupId(groupId);
					dao.save(o);
				}
			} else {
				dao.delete(o);
			}
		}
	}

	@Override
	@Transactional(readOnly = true)
	public OfficeGroupUser getUserDefaultGroupId(String userId) {
		StringBuilder sb = new StringBuilder();
		sb.append("and userId='").append(userId).append("' order by type");
		List<OfficeGroupUser> lt = dao.list(OfficeGroupUser.class, sb.toString(), 1, 1);
		if (lt.isEmpty()) {
			return null;
		}
		return lt.get(0);
	}
}